# coding=utf-8

from web.form import AttributeList
from controllers.admin.projects.models import Destination

def destination_render(template, dests = None, delimiter = u'— '):
    """
    按指定模板生成渲染代码
    """
    dests = dests or Destination.get_with_depth()
    if dests:
        def render(dests):
            x = ''
            if not dests:
                return ''

            for dest in dests:
                d = dest
                depth = ''
                while d.parent:
                    d = d.parent
                    depth += delimiter

                x += template % {'id': dest.id
                            , 'name': depth + dest.name
                            , 'type': dest.type}
                x += render(dest.child)

            return x

        return render(dests)

    return ''
            

def destination_dropdown(name
        , dests = None
        , val = None, dflt = u'无', dflt_val = u'0', **attrs):
    """
    生成并返回一个带层次结构的目的地选择的Dropdown控件

    @val, 默认选中值
    """
    attrs = AttributeList(attrs)
    if 'class_' in attrs:
        attrs['class'] = attrs['class_']
        del attrs['class_']

    attrs['name'] = name

    x = u'<select %s>\n' % attrs
    x += u'  <option value="%(val)s">%(text)s</option>\n' % {
                    'text': dflt,
                    'val': dflt_val
                    }

    dests = dests or Destination.get_with_depth()
    if dests:
        def render(dests):
            x = ''
            if not dests:
                return x
            
            for dest in dests:
                if dest.id == val:
                    select_p = ' selected="selected"'
                else: select_p = ''
                # 选项名
                d = dest
                # 深度文本
                depth = ''
                # 提取深度
                while d.parent:
                    d = d.parent
                    depth += '&nbsp;&nbsp;&nbsp;'

                x += u'  <option%s value="%s">%s</option>\n' % (select_p, dest.id, depth + dest.name)
                x += render(dest.child)

            return x

        x += render(dests)

    x += u'</select>\n'
    return x
